package my.soft.aiteacher.student.service.Impl;

import jakarta.annotation.Resource;
import my.soft.aiteacher.exception.BusinessException;
import my.soft.aiteacher.common.mapper.UserMapper;
import my.soft.aiteacher.student.service.IStarRatingsService;
import my.soft.aiteacher.common.mapper.VideoInformationMapper;
import my.soft.aiteacher.student.pojo.StarRatings;
import my.soft.aiteacher.student.mapper.StarRatingsMapper;
import my.soft.aiteacher.common.pojo.UserDo;
import my.soft.aiteacher.common.pojo.VideoInformationDo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 基础五星评分表 服务实现类
 * </p>
 *
 * @author GMCX
 * @since 2025-06-09
 */
@Service
public class StarRatingsServiceImpl extends ServiceImpl<StarRatingsMapper, StarRatings> implements IStarRatingsService {

    @Resource
    private StarRatingsMapper starRatingsMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserMapper userMapper;
    @Resource
    private VideoInformationMapper videoInformationMapper;

    @Override
    @Transactional
    public void upload(StarRatings starRatings) {
        UserDo userDo = userMapper.selectById(starRatings.getUserId());
        if (Objects.isNull(userDo)) {
            throw new BusinessException("用户不存在");
        }
        VideoInformationDo videoInformationDo = videoInformationMapper.selectById(starRatings.getVideoInfoId());
        if (Objects.isNull(videoInformationDo)) {
            throw new BusinessException("视频信息不存在");
        }
        Set<Object> members = redisTemplate.opsForSet()
                .members("StartRatings：" + starRatings.getVideoInfoId());
        if (Objects.nonNull(members)) {
            members.stream()
                    .filter(member -> ((StarRatings) member).getUserId().equals(starRatings.getUserId()))
                    .findFirst()
                    .ifPresent(member -> {
                        throw new BusinessException("您已经评分过该视频");
                    });
        }


        redisTemplate.opsForSet().add("StartRatings：" + starRatings.getVideoInfoId(), starRatings);
        starRatingsMapper.insert(starRatings);
    }
}
